/**
 * SmarTest Studio - 报告页面脚本
 * 实现测试报告的交互功能，包括图表渲染、测试用例详情查看等
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    initCharts();
    
    // 初始化测试用例详情模态框
    initCaseDetailModal();
    
    // 初始化导出功能
    initExportButtons();
});

/**
 * 初始化结果统计图表
 */
function initCharts() {
    // 结果饼图
    const resultCtx = document.getElementById('resultChart').getContext('2d');
    const resultChart = new Chart(resultCtx, {
        type: 'pie',
        data: {
            labels: ['通过', '部分通过', '失败'],
            datasets: [{
                data: [12, 2, 1],
                backgroundColor: [
                    'rgba(75, 192, 192, 0.8)',
                    'rgba(255, 206, 86, 0.8)',
                    'rgba(255, 99, 132, 0.8)'
                ],
                borderColor: [
                    'rgba(75, 192, 192, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(255, 99, 132, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom',
                },
                title: {
                    display: true,
                    text: '测试结果分布'
                }
            }
        }
    });

    // 性能图表
    const performanceCtx = document.getElementById('performanceChart').getContext('2d');
    const performanceChart = new Chart(performanceCtx, {
        type: 'bar',
        data: {
            labels: ['启动时间', '响应时间', '内存占用', 'CPU占用', '电量消耗'],
            datasets: [{
                label: '实际值',
                data: [5, 2.5, 150, 25, 15],
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }, {
                label: '目标值',
                data: [3, 1, 100, 20, 10],
                backgroundColor: 'rgba(153, 102, 255, 0.5)',
                borderColor: 'rgba(153, 102, 255, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    position: 'bottom',
                },
                title: {
                    display: true,
                    text: '性能指标对比'
                }
            }
        }
    });
}

/**
 * 初始化测试用例详情模态框
 */
function initCaseDetailModal() {
    const caseDetailModal = document.getElementById('caseDetailModal');
    if (!caseDetailModal) return;
    
    // 模态框显示事件
    caseDetailModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        const caseId = button.getAttribute('data-case-id');
        
        // 加载测试用例详情数据
        loadCaseDetail(caseId);
    });
}

/**
 * 加载测试用例详情数据
 * @param {string} caseId - 测试用例ID
 */
function loadCaseDetail(caseId) {
    // 模拟UiTest请求，实际项目中应替换为真实的API调用
    // http.get(`/api/testcases/${caseId}`)
    //     .then(response => {
    //         updateCaseDetailUI(response.data);
    //     })
    //     .catch(error => {
    //         console.error('加载测试用例详情失败:', error);
    //     });
    
    // 使用模拟数据
    const mockData = getMockCaseData(caseId);
    updateCaseDetailUI(mockData);
}

/**
 * 更新测试用例详情UI
 * @param {Object} caseData - 测试用例数据
 */
function updateCaseDetailUI(caseData) {
    // 更新基本信息
    document.getElementById('caseTitle').textContent = caseData.title;
    document.getElementById('caseId').textContent = caseData.id;
    document.getElementById('caseDescription').textContent = caseData.description;
    document.getElementById('caseExecutionTime').textContent = caseData.executionTime;
    
    // 更新状态标签
    const statusElement = document.getElementById('caseStatus');
    statusElement.textContent = caseData.status;
    statusElement.className = 'status-badge';
    if (caseData.status === '通过') {
        statusElement.classList.add('status-passed');
    } else if (caseData.status === '失败') {
        statusElement.classList.add('status-failed');
    } else {
        statusElement.classList.add('status-partial');
    }
    
    // 更新执行活动
    const stepsContainer = document.getElementById('caseSteps');
    stepsContainer.innerHTML = '';
    caseData.steps.forEach(step => {
        const li = document.createElement('li');
        li.textContent = step.description;
        
        // 添加活动状态
        const statusSpan = document.createElement('span');
        statusSpan.className = 'step-status';
        if (step.status === '通过') {
            statusSpan.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i>';
        } else if (step.status === '失败') {
            statusSpan.innerHTML = '<i class="bi bi-x-circle-fill text-danger"></i>';
        } else {
            statusSpan.innerHTML = '<i class="bi bi-dash-circle-fill text-warning"></i>';
        }
        li.appendChild(statusSpan);
        
        stepsContainer.appendChild(li);
    });
    
    // 更新截图
    const screenshotsContainer = document.getElementById('caseScreenshots');
    screenshotsContainer.innerHTML = '';
    caseData.screenshots.forEach(screenshot => {
        const screenshotDiv = document.createElement('div');
        screenshotDiv.className = 'screenshot';
        
        const img = document.createElement('img');
        img.src = screenshot.url;
        img.alt = screenshot.description;
        screenshotDiv.appendChild(img);
        
        const caption = document.createElement('div');
        caption.className = 'screenshot-caption';
        caption.textContent = screenshot.description;
        screenshotDiv.appendChild(caption);
        
        screenshotsContainer.appendChild(screenshotDiv);
    });
    
    // 更新日志
    document.getElementById('caseLogs').textContent = caseData.logs;
}

/**
 * 获取模拟测试用例数据
 * @param {string} caseId - 测试用例ID
 * @returns {Object} 测试用例数据
 */
function getMockCaseData(caseId) {
    // 模拟数据，实际项目中应从API获取
    const mockCases = {
        '1': {
            id: '1',
            title: '启动应用测试',
            description: '验证应用能否正常启动',
            status: '通过',
            executionTime: '5秒',
            steps: [
                { description: '点击应用图标', status: '通过' },
                { description: '等待应用启动', status: '通过' },
                { description: '验证首页元素是否显示', status: '通过' }
            ],
            screenshots: [
                { url: '/img/screenshots/placeholder.svg', description: '启动前' },
                { url: '/img/screenshots/placeholder.svg', description: '启动中' },
                { url: '/img/screenshots/placeholder.svg', description: '启动完成' }
            ],
            logs: '[INFO] 2023-05-10 10:15:30 - 开始测试\n[INFO] 2023-05-10 10:15:31 - 点击应用图标\n[INFO] 2023-05-10 10:15:32 - 应用开始启动\n[INFO] 2023-05-10 10:15:35 - 应用启动完成\n[INFO] 2023-05-10 10:15:35 - 测试通过'
        },
        '2': {
            id: '2',
            title: '登录功能测试',
            description: '验证用户登录功能',
            status: '通过',
            executionTime: '10秒',
            steps: [
                { description: '点击登录按钮', status: '通过' },
                { description: '输入用户名和密码', status: '通过' },
                { description: '点击提交按钮', status: '通过' },
                { description: '验证登录成功', status: '通过' }
            ],
            screenshots: [
                { url: '/img/screenshots/placeholder.svg', description: '登录界面' },
                { url: '/img/screenshots/placeholder.svg', description: '输入信息' },
                { url: '/img/screenshots/placeholder.svg', description: '登录成功' }
            ],
            logs: '[INFO] 2023-05-10 10:20:00 - 开始测试\n[INFO] 2023-05-10 10:20:01 - 点击登录按钮\n[INFO] 2023-05-10 10:20:03 - 输入用户名和密码\n[INFO] 2023-05-10 10:20:05 - 点击提交按钮\n[INFO] 2023-05-10 10:20:08 - 验证登录成功\n[INFO] 2023-05-10 10:20:10 - 测试通过'
        },
        '3': {
            id: '3',
            title: '导航菜单测试',
            description: '验证导航菜单功能',
            status: '通过',
            executionTime: '8秒',
            steps: [
                { description: '点击菜单按钮', status: '通过' },
                { description: '验证菜单项是否显示', status: '通过' },
                { description: '点击各个菜单项', status: '通过' },
                { description: '验证页面跳转', status: '通过' }
            ],
            screenshots: [
                { url: '/img/screenshots/placeholder.svg', description: '菜单关闭状态' },
                { url: '/img/screenshots/placeholder.svg', description: '菜单打开状态' },
                { url: '/img/screenshots/placeholder.svg', description: '菜单点击后' }
            ],
            logs: '[INFO] 2023-05-10 10:30:00 - 开始测试\n[INFO] 2023-05-10 10:30:01 - 点击菜单按钮\n[INFO] 2023-05-10 10:30:02 - 验证菜单项显示\n[INFO] 2023-05-10 10:30:04 - 点击菜单项\n[INFO] 2023-05-10 10:30:06 - 验证页面跳转\n[INFO] 2023-05-10 10:30:08 - 测试通过'
        },
        '4': {
            id: '4',
            title: '表单提交测试',
            description: '验证表单提交功能',
            status: '部分通过',
            executionTime: '15秒',
            steps: [
                { description: '打开表单页面', status: '通过' },
                { description: '输入表单数据', status: '通过' },
                { description: '点击提交按钮', status: '通过' },
                { description: '验证表单验证', status: '部分通过' },
                { description: '验证提交结果', status: '部分通过' }
            ],
            screenshots: [
                { url: '/img/screenshots/placeholder.svg', description: '表单页面' },
                { url: '/img/screenshots/placeholder.svg', description: '输入数据' },
                { url: '/img/screenshots/placeholder.svg', description: '提交结果' }
            ],
            logs: '[INFO] 2023-05-10 10:40:00 - 开始测试\n[INFO] 2023-05-10 10:40:02 - 打开表单页面\n[INFO] 2023-05-10 10:40:05 - 输入表单数据\n[INFO] 2023-05-10 10:40:08 - 点击提交按钮\n[WARNING] 2023-05-10 10:40:10 - 部分字段验证不完整\n[WARNING] 2023-05-10 10:40:12 - 提交结果部分符合预期\n[INFO] 2023-05-10 10:40:15 - 测试部分通过'
        },
        '5': {
            id: '5',
            title: '性能测试',
            description: '验证应用性能',
            status: '失败',
            executionTime: '30秒',
            steps: [
                { description: '启动应用', status: '通过' },
                { description: '执行性能测试脚本', status: '通过' },
                { description: '收集性能数据', status: '通过' },
                { description: '验证性能指标', status: '失败' }
            ],
            screenshots: [
                { url: '/img/screenshots/placeholder.svg', description: '性能测试开始' },
                { url: '/img/screenshots/placeholder.svg', description: '性能测试中' },
                { url: '/img/screenshots/placeholder.svg', description: '性能测试结果' }
            ],
            logs: '[INFO] 2023-05-10 11:00:00 - 开始测试\n[INFO] 2023-05-10 11:00:05 - 启动应用\n[INFO] 2023-05-10 11:00:10 - 执行性能测试脚本\n[INFO] 2023-05-10 11:00:20 - 收集性能数据\n[ERROR] 2023-05-10 11:00:25 - 响应时间超过阈值: 实际2.5秒, 预期1秒\n[ERROR] 2023-05-10 11:00:28 - 内存占用超过阈值: 实际150MB, 预期100MB\n[INFO] 2023-05-10 11:00:30 - 测试失败'
        }
    };
    
    return mockCases[caseId] || {
        id: caseId,
        title: '未知测试用例',
        description: '无描述',
        status: '未知',
        executionTime: '0秒',
        steps: [],
        screenshots: [],
        logs: '无日志数据'
    };
}

/**
 * 初始化导出按钮功能
 */
function initExportButtons() {
    // PDF导出按钮
    const pdfButton = document.querySelector('button[title="导出PDF"]');
    if (pdfButton) {
        pdfButton.addEventListener('click', exportToPDF);
    }
    
    // Excel导出按钮
    const excelButton = document.querySelector('button[title="导出Excel"]');
    if (excelButton) {
        excelButton.addEventListener('click', exportToExcel);
    }
    
    // 打印按钮
    const printButton = document.querySelector('button[title="打印"]');
    if (printButton) {
        printButton.addEventListener('click', printReport);
    }
    
    // 测试用例详情导出按钮
    const exportDetailButton = document.querySelector('#caseDetailModal .btn-primary');
    if (exportDetailButton) {
        exportDetailButton.addEventListener('click', exportCaseDetail);
    }
}

/**
 * 导出报告为PDF
 */
function exportToPDF() {
    // 实际项目中应实现PDF导出功能
    alert('导出PDF功能将在后续版本中实现');
}

/**
 * 导出报告为Excel
 */
function exportToExcel() {
    // 实际项目中应实现Excel导出功能
    alert('导出Excel功能将在后续版本中实现');
}

/**
 * 打印报告
 */
function printReport() {
    window.print();
}

/**
 * 导出测试用例详情
 */
function exportCaseDetail() {
    // 实际项目中应实现测试用例详情导出功能
    alert('导出测试用例详情功能将在后续版本中实现');
}